import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:flutter/cupertino.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';

class NewsList extends StatefulWidget {
  NewsList({Key key, this.newType}) : super(key: key);
  String newType;

  @override
  State<StatefulWidget> createState() => new NewsListState();
}

class NewsListState extends State<NewsList> {
  //自定义文字大小
  final TextStyle _textFont = new TextStyle(fontSize: 10.0);
  //存放新闻数据
  List newsData = [];

  @override
  void initState() {
    super.initState();
    _loadData(widget.newType);
  }

  //根据api接口下载数据
  Future _loadData(String newType) async {
    String _loadUrl = 'http://v.juhe.cn/toutiao/index?' +
        'type=${newType}' +
        '&key=3a86f36bd3ecac8a51135ded5eebe862';
    http.Response response = await http.get(_loadUrl);
    var result = json.decode(response.body);
    setState(() {
      newsData = result['result']['data'];
    });
  }

  @override
  Widget build(BuildContext context) {
    if (newsData.length != 0) {
      return new ListView.builder(
        itemCount: newsData.length,
        itemBuilder: (context, index) {
          return newsItem(newsData[index]);
        },
      );
    } else {
      return new CupertinoActivityIndicator();
    }
  }

  //定义每个新闻内容的布局
  newsItem(var data) {
    //定义新闻item左边树状布局结构，包含时间、标题和来源
    var column = Container(
      child: new Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: <Widget>[
          new Text(
            '时间：${data['date']}',
            style: _textFont,
          ),
          new Text(
            data['title'],
            maxLines: 2,
            style: new TextStyle(fontWeight: FontWeight.w500),
          ),
          new Text(
            '来源：${data['author_name']}',
            style: _textFont,
          ),
        ],
      ),
    );

    //定义整个新闻item的布局结构
    var content = Container(
      height: 120.0,
      child: new Row(
        children: <Widget>[
          new Expanded(
            child: column,
            flex: 2,
          ),
          new Expanded(
            child: new ClipRRect(
              borderRadius: new BorderRadius.circular(5.0),
              child: new Image.network(
                data['thumbnail_pic_s'],
                fit: BoxFit.fill,
              ),
            ),
            flex: 1,
          )
        ],
      ),
    );

    //将新闻内容用card包装起来，并提供一个手势监测，这里用于点击进入查看新闻详情
    return new Card(
      child: new GestureDetector(
        child: content,
        onTap: newContent(data),
      ),
    );
  }

  newContent(var data) {
    return new WebviewScaffold(url: data['url']);
  }
}
